var visualizer;
var prevX, prevY;
var zoomMin=50;
var zoomMax=70;
var zoomVar=60;

var mouseMove = function(e) {
    var x, y;
    if (e.offsetX || e.offsetY === 0) {
        x = e.x;
        y = e.y;
    }
    var newX = visualizer.x + (prevX - x) / visualizer.ratio;
    var newY = visualizer.y + (prevY - y) / visualizer.ratio;
    if (newX + visualizer.w >= motorGP.mapWidth)
        visualizer.x = motorGP.mapWidth - visualizer.w;
    else if (newX <= 0)
        visualizer.x = 0;
    else
        visualizer.x = newX;
    if (newY + visualizer.h >= motorGP.mapHeight)
        visualizer.y = motorGP.mapHeight - visualizer.h;
    else if (newY <= 0)
        visualizer.y = 0;
    else
        visualizer.y = newY;
    motorGP.mapCanvas.clearCanvas();
    motorGP.vehicleCanvas.clearCanvas();
    motorGP.routesCanvas.clearCanvas();
    visualizer.draw();
    prevX = x;
    prevY = y;
};

var mouseDown = function(e) {
    prevX = e.x;
    prevY = e.y;
    motorGP.vehicleCanvas.canvas.addEventListener("mousemove", mouseMove, false);
};
var mouseUp = function(e) {
    motorGP.vehicleCanvas.canvas.removeEventListener("mousemove", mouseMove);
};

var mouseWheel = function(e) {
    var factor;
    var delta = e.wheelDelta / 20;
    if (delta <= 0) {
        factor = 1 / Math.abs(delta);
    }
    else {
        factor = Math.abs(delta);
    }
    visualizer.w = visualizer.w * factor;
    visualizer.h = visualizer.h * factor;
    motorGP.mapCanvas.clearCanvas();
    motorGP.vehicleCanvas.clearCanvas();
    motorGP.routesCanvas.clearCanvas();
    visualizer.draw();
};

var resizeWindow = function(e) {
    var canvases = [];
    canvases.push(motorGP.mapCanvas);
    canvases.push(motorGP.routesCanvas);
    canvases.push(motorGP.vehicleCanvas);

    var h, w;
    if (window.innerHeight < window.innerWidth * 9 / 16) {
        h = window.innerHeight * 0.9;
        w = h * 16 / 9;
    }
    else {
        w = window.innerWidth * 0.9;
        h = w * 9 / 16;
    }

    for (var i = 0; i < 3; i++) {
        canvases[i].canvas.height = h;
        canvases[i].canvas.width = w;
    }
    motorGP.mapCanvas.clearCanvas();
    motorGP.vehicleCanvas.clearCanvas();
    motorGP.routesCanvas.clearCanvas();
    visualizer.draw();
};
function redraw(canvas)
{
    var ctx = canvas.getContext("2d");
    // limpiar el canvas
    var p1 = ctx.transformedPoint(0, 0);
    var p2 = ctx.transformedPoint(canvas.width, canvas.height);
    ctx.clearRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);

    ctx.lineWidth = 0.5;
    ctx.strokeStyle = "#EEEEEE";


    // horizontal grid lines
    for (var i = 0; i <= canvas.height; i = i + 10)
    {
        ctx.beginPath();
        ctx.moveTo(0, i);
        ctx.lineTo(canvas.width, i);
        if (i % parseInt(50) === 0) {
            ctx.lineWidth = 2;
        } else {
            ctx.lineWidth = 0.5;
        }
        //ctx.closePath();
        ctx.stroke();
        ctx.save();
        ctx.restore();
    }

    // vertical grid lines
    for (var j = 0; j <= canvas.width; j = j + 10)
    {
        ctx.beginPath();
        ctx.moveTo(j, 0);
        ctx.lineTo(j, canvas.height);
        if (j % parseInt(50) === 0) {
            ctx.lineWidth = 2;
        } else {
            ctx.lineWidth = 0.5;
        }
        ctx.closePath();
        ctx.stroke();
    }

}

function initCanvas(canvas) {
    var ctx = canvas.getContext("2d");
    var lastX = canvas.width / 2, lastY = canvas.height / 2;
    var dragStart, dragged;
    canvas.addEventListener('mousedown', function(evt) {
        document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect = 'none';
        lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
        lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
        dragStart = ctx.transformedPoint(lastX, lastY);
        dragged = false;
    }, false);
    canvas.addEventListener('mousemove', function(evt) {
        lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
        lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
        dragged = true;
        if (dragStart) {
            var pt = ctx.transformedPoint(lastX, lastY);
            ctx.translate(pt.x - dragStart.x, pt.y - dragStart.y);
            redraw(canvas);
        }
    }, false);
    canvas.addEventListener('mouseup', function(evt) {
        dragStart = null;
        if (!dragged)
            zoom(evt.shiftKey ? -1 : 1);
    }, false);

    var scaleFactor = 1.1;
    var zoom = function(clicks) {
		if (clicks>0){
            if (zoomMax === zoomVar) return;
            if (zoomVar+clicks>zoomMax){
                clicks=zoomMax-zoomVar; // limitar clicks hasta donde se pueda
                zoomVar=zoomMax;
            }else{
                zoomVar+=clicks;
            }
        }else{
            if (zoomMin === zoomVar) return;
            if (zoomVar+clicks<zoomMin){
                clicks=-zoomMin+zoomVar; // limitar clicks hasta donde se pueda
                zoomVar=zoomMin;
            }else{
                zoomVar+=clicks;
            }
        }
        var pt = ctx.transformedPoint(lastX, lastY);
        ctx.translate(pt.x, pt.y);
        var factor = Math.pow(scaleFactor, clicks);
        ctx.scale(factor, factor);
        ctx.translate(-pt.x, -pt.y);
        
        redraw(canvas);
    };

    var handleScroll = function(evt) {
        var delta = evt.wheelDelta ? evt.wheelDelta / 40 : evt.detail ? -evt.detail : 0;
        if (delta)
            zoom(delta);
        return evt.preventDefault() && false;
    };
    canvas.addEventListener('DOMMouseScroll', handleScroll, false);
    canvas.addEventListener('mousewheel', handleScroll, false);
}
function trackTransforms(ctx) {
    var svg = document.createElementNS("http://www.w3.org/2000/svg", 'svg');
    var xform = svg.createSVGMatrix();
    ctx.getTransform = function() {
        return xform;
    };

    var savedTransforms = [];
    var save = ctx.save;
    ctx.save = function() {
        savedTransforms.push(xform.translate(0, 0));
        return save.call(ctx);
    };
    var restore = ctx.restore;
    ctx.restore = function() {
        xform = savedTransforms.pop();
        return restore.call(ctx);
    };

    var scale = ctx.scale;
    ctx.scale = function(sx, sy) {
        xform = xform.scaleNonUniform(sx, sy);
        return scale.call(ctx, sx, sy);
    };
    var rotate = ctx.rotate;
    ctx.rotate = function(radians) {
        xform = xform.rotate(radians * 180 / Math.PI);
        return rotate.call(ctx, radians);
    };
    var translate = ctx.translate;
    ctx.translate = function(dx, dy) {
        xform = xform.translate(dx, dy);
        return translate.call(ctx, dx, dy);
    };
    var transform = ctx.transform;
    ctx.transform = function(a, b, c, d, e, f) {
        var m2 = svg.createSVGMatrix();
        m2.a = a;
        m2.b = b;
        m2.c = c;
        m2.d = d;
        m2.e = e;
        m2.f = f;
        xform = xform.multiply(m2);
        return transform.call(ctx, a, b, c, d, e, f);
    };
    var setTransform = ctx.setTransform;
    ctx.setTransform = function(a, b, c, d, e, f) {
        xform.a = a;
        xform.b = b;
        xform.c = c;
        xform.d = d;
        xform.e = e;
        xform.f = f;
        return setTransform.call(ctx, a, b, c, d, e, f);
    };
    var pt = svg.createSVGPoint();
    ctx.transformedPoint = function(x, y) {
        pt.x = x;
        pt.y = y;
        return pt.matrixTransform(xform.inverse());
    };
}
var addCanvasP = function() {
    motorGP.loadImages();
    visualizer = new Visualizer(0, 0, 200000, 200000);
    var div = document.getElementById("divMapa");
    var mapCanvas = new Canvas(document.createElement("canvas"));
    mapCanvas.canvas.id = "mapCanvas";
    var routesCanvas = new Canvas(document.createElement("canvas"));
    routesCanvas.canvas.id = "routesCanvas";
    var vehicleCanvas = new Canvas(document.createElement("canvas"));
    vehicleCanvas.canvas.id = "vehicleCanvas";

    var canvases = [];
    canvases.push(mapCanvas);
    canvases.push(routesCanvas);
    canvases.push(vehicleCanvas);

    var h, w;
    if (window.innerHeight < window.innerWidth * 9 / 16) {
        h = window.innerHeight * 0.9;
        w = h * 16 / 9;
    }
    else {
        w = window.innerWidth * 0.9;
        h = w * 9 / 16;
    }

    for (var i = 0; i < 3; i++) {
        var ctx = canvases[i].canvas.getContext("2d");
        canvases[i].canvas.style.position = "absolute";
        canvases[i].canvas.style.background = "transparent";

        canvases[i].canvas.height = h;
        canvases[i].canvas.width = w;


        canvases[i].canvas.style.border = "1px solid #000000";
        div.appendChild(canvases[i].canvas);
        trackTransforms(ctx);
        initCanvas(canvases[i].canvas);
    }

    //

    mapCanvas.canvas.style.zIndex = -2;
    routesCanvas.canvas.style.zIndex = -1;
    vehicleCanvas.canvas.style.zIndex = 0;


    motorGP.mapCanvas = mapCanvas;
    motorGP.routesCanvas = routesCanvas;
    motorGP.vehicleCanvas = vehicleCanvas;
    window.onresize = resizeWindow;
    motorGP.initNodeArray();
};
